<script setup lang="ts">
import type { AgentBaseInfo, TrainAgentInfo } from "@/common/apis/intelligent/type"
import type { UploadType } from "@@/constants/other-keys"
import type { FormInstance, FormRules, UploadUserFile } from "element-plus"
import { getAgentInfoApi, getAgentTypeOptionsApi, trainedDeleteApi, trainedDownloadApi, trainedListApi, trainedPublishApi, updateAgentDataApi } from "@/common/apis/intelligent"
import { usePagination } from "@/common/composables/usePagination"
import { getProjectId } from "@/common/utils/cache/local-storage"
import { useRoute } from "vue-router"
import { downloadFile, filesToZip } from "@/common/utils/fileUtils"
import UploadFolder from "@@/components/UploadFolder/index.vue"
import { agentSupportSide, agentSupportSideMap } from "@@/constants/other-keys"
import { Search } from "@element-plus/icons-vue"
import { cloneDeep, isEmpty } from "lodash-es"

interface Props {
  agent_id: string
  agentName: string
  publishAgents: TrainAgentInfo[]
}
const route = useRoute()
const props = defineProps<Props>()
const emit = defineEmits(["update:publishAgents", "update:agentName"])

const DEFAULT_FORM_DATA: AgentBaseInfo = {
  agent_id: props.agent_id,
  agent_name: "",
  agent_code: "",
  agent_type: "",
  agent_support_side: "3",
  agent_describe: "",
  agent_image_id: ""
}
const detailLoading = ref<boolean>(false)
const loading = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<AgentBaseInfo>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<AgentBaseInfo> = {
  agent_name: [{ required: true, trigger: "blur", message: "请输入智能体名称" }],
  agent_code: [{ required: true, trigger: "blur", message: "请输入智能体类名" }],
  agent_type: [{ required: true, trigger: "change", message: "请选择智能体类型" }],
  agent_support_side: [{ required: true, trigger: "change", message: "请选择支持阵营" }]
}
const agentTypeOptions = ref<string[]>([])
const uploadType = ref<UploadType>()
const fileList = ref<UploadUserFile[]>([])
const trained_agent_name = ref<string>()
const tableData = ref<TrainAgentInfo[]>([])
const multipleSelection = ref<TrainAgentInfo[]>([])
const isEdit = ref<boolean>(false)
const defaultFormData = ref<AgentBaseInfo>()
const TableRef = ref()

const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

async function getParam(): Promise<FormData> {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve) => {
    const params = new FormData()
    params.append("agent_id", props.agent_id)
    if (!isEmpty(getProjectId())) {
      params.append("project_id", getProjectId())
    }
    params.append("agent_name", formData.value.agent_name)
    params.append("agent_code", formData.value.agent_code)
    params.append("describe", formData.value.agent_describe)
    params.append("agent_type", formData.value.agent_type)
    params.append(`agent_support_side`, formData.value.agent_support_side)
    resolve(params)
  })
}

// 保存
async function handleEditSave() {
  formRef.value?.validate(async (valid: boolean, fields: any) => {
    if (!valid) return console.error("表单校验不通过", fields)
    const params: FormData = await getParam()
    updateAgentDataApi(params)
      .then(() => {
        getAgentInfo()
        isEdit.value = false
        ElMessage.success("操作成功")
      })
      .finally(() => { })
  })
}

function getAgentInfo() {
  detailLoading.value = true
  props.agent_id
  && getAgentInfoApi(props.agent_id)
    .then(({ data }) => {
      if (data) {
        formData.value = cloneDeep(data)
        formData.value.agent_support_side = `${data.agent_support_side}`
        emit("update:agentName", formData.value.agent_name)
      } else {
        ElMessage("数据不存在")
      }
    })
    .finally(() => {
      detailLoading.value = false
    })
}

function getAgentTypeOptions() {
  getAgentTypeOptionsApi().then(({ data }) => {
    agentTypeOptions.value = data.type
  })
}

function getTrainedList() {
  loading.value = true
  const params = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    trained_agent_name: trained_agent_name.value,
    trained_agent_code: formData.value.agent_code
  }
  trainedListApi(props.agent_id, params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .finally(() => {
      loading.value = false
    })
}
// 查询
function handleSearch() {
  paginationData.currentPage === 1 ? getTrainedList() : (paginationData.currentPage = 1)
}
function handleSelectionChange(val: any) {
  multipleSelection.value = val
  emit("update:publishAgents", multipleSelection.value)
}
// 下载
function handleDownload(row: TrainAgentInfo) {
  trainedDownloadApi(props.agent_id, {
    trained_agent_ids: [row.trained_agent_id],
    file_name: row.trained_agent_files_path
  }).then((res) => {
    downloadFile(res)
  })
}
// 发布
function handlePublish(id: string) {
  const ids: string[] = []
  if (id != "1") {
    ids.push(id)
  } else {
    multipleSelection.value.forEach((item) => {
      ids.push(item.trained_agent_id as string)
    })
  }
  const params = { agent_id: props.agent_id, ids }
  trainedPublishApi(params).then(() => {
    ElMessage.success("发布成功")
    getTrainedList()
    handleClearSelection()
  })
}
function handleDelete(name: string, id: string) {
  ElMessageBox.confirm(`正在删除智能体：${name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const ids: string[] = []
      ids.push(id)
      const params = {
        agent_id: props.agent_id,
        ids
      }
      trainedDeleteApi(params).then(() => {
        ElMessage.success("删除成功")
        getTrainedList()
      })
    })
    .catch(() => {
      ElMessage.info("取消删除")
    })
}
// double 类型
function formatter(row: any) {
  const version = row.trained_agent_version
  // 判断是否为整数且非小数（单精度），转换为 double 类型
  if (Number.isInteger(version)) {
    return `${version}.0` // 转换为 double 格式
  }
  return version // 已经是 double 类型的则不处理
}
function getRowKeys(row: TrainAgentInfo) {
  return row.trained_agent_id
}
function handleEdit() {
  defaultFormData.value = cloneDeep(formData.value)
  isEdit.value = true
}
function handleEditCancel() {
  isEdit.value = false
  getAgentInfo()
}

function handleClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}

onMounted(() => {
  nextTick(() => {
    getAgentInfo()
    getAgentTypeOptions()
  })
})

const isProject = computed(() => {
  return getProjectId() != null
})

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTrainedList, { immediate: true })

watch(
  () => props.agent_id,
  () => {
    nextTick(() => {
      getAgentInfo()
      getAgentTypeOptions()
      handleSearch()
      handleClearSelection()
    })
  }
)

onActivated(() => {
  if (props.agent_id !== route.query.id) {
    isEdit.value = false
    getAgentInfo()
  }
})
defineExpose({ handleClearSelection })
</script>

<template>
  <div class="version-wrapper">
    <div class="cpi-header">
      <div class="flex-center gap-1">
        <el-icon :size="18">
          <ElementPlus />
        </el-icon>
        基本信息
      </div>
      <el-space>
        <el-button v-if="isProject && isEdit" v-throttle="() => handleEditCancel()">
          取消保存
        </el-button>
        <el-button v-if="isProject && isEdit" type="primary" v-throttle="() => handleEditSave()">
          保存
        </el-button>
        <el-button v-if="isProject && !isEdit" type="primary" v-throttle="() => handleEdit()">
          编辑
        </el-button>
      </el-space>
    </div>
    <el-form v-if="isEdit" ref="formRef" :model="formData" :rules="formRules" width="600" label-width="120px" label-position="top" :close-on-click-modal="false">
      <el-row :gutter="24">
        <el-col :sm="24" :lg="12">
          <el-row :gutter="24">
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体名称" prop="agent_name">
                <el-input placeholder="请输入" v-model="formData.agent_name" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体类名" prop="agent_code">
                <el-input placeholder="请输入" v-model="formData.agent_code" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体类型" prop="agent_type">
                <el-select
                  v-model="formData.agent_type" clearable placeholder="请选择"
                  popper-class="drawer-select-popper"
                >
                  <el-option v-for="item in agentTypeOptions" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="支持阵营" prop="agent_support_side">
                <el-select
                  v-model="formData.agent_support_side" clearable placeholder="请选择"
                  popper-class="drawer-select-popper"
                >
                  <el-option
                    v-for="item in agentSupportSide" :key="item.value" :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :sm="24" :md="12" :lg="12">
          <el-form-item label="智能体描述" prop="agent_describe">
            <el-input v-model="formData.agent_describe" type="textarea" maxlength="600" :rows="5" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form v-else class="view-form" ref="formRef" width="600" label-width="120px" label-position="top" :close-on-click-modal="false">
      <el-row :gutter="24">
        <el-col :sm="24" :lg="12">
          <el-row :gutter="24">
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体名称：" prop="agent_name">
                <span :title="$getViewText(formData.agent_name)">{{ $getViewText(formData.agent_name) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体类名：" prop="agent_code">
                <span :title="$getViewText(formData.agent_code)">{{ $getViewText(formData.agent_code) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="智能体类型：" prop="agent_type">
                <span :title="$getViewText(formData.agent_type)">{{ $getViewText(formData.agent_type) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="12">
              <el-form-item label="支持阵营：" prop="agent_support_side">
                <span :title="$getViewText(agentSupportSideMap[formData.agent_support_side])">{{ $getViewText(agentSupportSideMap[formData.agent_support_side]) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :sm="24" :md="12" :lg="12">
          <el-form-item label="智能体描述：" prop="agent_describe" class="el-form-item_full-width">
            <span :title="$getViewText(formData.agent_describe)">{{ $getViewText(formData.agent_describe) }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="cpi-header">
      <div class="flex-center gap-1">
        <el-icon :size="18">
          <ElementPlus />
        </el-icon>
        版本管理
      </div>
      <div>
        <div class="cc-search-common">
          <el-input v-model="trained_agent_name" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </div>
    </div>
    <div class="cpi-content-main">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table
            ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
            :height="height" @selection-change="handleSelectionChange"
          >
            <el-table-column v-if="isProject" type="selection" align="center" :reserve-selection="true" width="55" />
            <el-table-column prop="trained_agent_name" label="智能体名称" show-overflow-tooltip />
            <el-table-column prop="create_time" label="时间" show-overflow-tooltip />
            <el-table-column prop="trained_agent_version" :formatter="formatter" label="版本号" header-align="left" />
            <el-table-column prop="trained_agent_reward" label="奖励" show-overflow-tooltip />
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-space :size="12">
                  <el-link :underline="false" @click.stop="handleDownload(scope.row)" title="下载">
                    <el-icon :size="18">
                      <Download />
                    </el-icon>
                  </el-link>
                  <el-link
                    :underline="false" v-if="isProject"
                    @click.stop="handlePublish(scope.row.trained_agent_id)" title="发布"
                  >
                    <el-icon :size="18">
                      <Promotion />
                    </el-icon>
                  </el-link>
                  <el-link
                    :underline="false" type="danger" @click.stop="
                      handleDelete(
                        scope.row.trained_agent_name,
                        scope.row.trained_agent_id,
                      )
                    " title="删除"
                  >
                    <el-icon :size="18">
                      <Delete />
                    </el-icon>
                  </el-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-auto-resizer>
    </div>
    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :disabled="loading"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.version-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: calc(var(--footer-pager) - 1px - 10px);
}
.pager-wrapper {
  padding-bottom: 0px !important;
  height: auto !important;
  width: calc(100%) !important;
}
.el-form {
  background: var(--el-bg-color);
  padding: var(--main-padding) 30px 0 30px;
  border-radius: 4px 4px 4px 4px;
  margin-bottom: var(--main-padding);
}
:deep(.view-form .el-form-item__label) {
  color: #a1accc !important;
}
:deep(.view-form .el-form-item__content) {
  & > span {
    width: 100%;
    @extend %ellipsis;
  }
}
:deep(.view-form .el-form-item_full-width .el-form-item__content) {
  overflow: hidden;
  & > span {
    display: -webkit-box; /* 使元素成为弹性盒子 */
    -webkit-box-orient: vertical; /* 设置盒子方向为垂直 */
    -webkit-line-clamp: 3; /* 限制显示的行数为 3 行 */
    overflow: hidden; /* 隐藏超出部分 */
    text-overflow: ellipsis; /* 显示省略号 */
    text-wrap: wrap;
  }
}
</style>
